﻿$(function () {
    $('#liveChatButton').click(function () {

        var width = $(this).attr('data-width');
        var height = $(this).attr('data-height');

        $('<div />', {
            id: 'liveChatOverlay'
        }).appendTo('body');

        $('<iframe />', {
            id: "iframeLiveChat",
            src: "/activechatclient",
            style: "width: " + width + "px; height: " + height + "px; margin-left: -" + (width / 2) + "px; margin-top: -" + (height / 2) + "px"
        }).appendTo('body');

    });
});

var liveChatClient = {

    config: {
        clientIP: null,
        sessionId: null,
        coBrowsing: false,
        operatorConnectionId: null
    },

    sendOffLineMessage: function(name, email, message) {
        $.getJSON('/SendOfflineMessage', {name: name, email: email, message: message}, function (result) {
            alert('Your message has been sent. Thank you.');
            $('#iframeLiveChat, #liveChatOverlay', window.parent.document).remove();
        });
    },

    updateCoBrowsingLink: function (url) {
        var liveChat = $.connection.livechat;
        liveChat.server.sendMessage('Client is now browsing: ' + url, liveChatClient.config.operatorConnectionId, $.connection.hub.id, 'System', 'info', liveChatClient.config.sessionId);
    },

    init: function (newConfig) {

        if (typeof (newConfig == 'object'))
            this.config = newConfig;

        var liveChat = $.connection.livechat;
        var clientName;
        var operatorConnectionId;
        var inChat = false;
        var typingIndicationTimer;
        var keyStrokeCount = 0;

        $('.close').click(function () {
            liveChat.server.endChat($.connection.hub.id);
            $('#iframeLiveChat, #liveChatOverlay, #iframeLiveChatBrowse', window.parent.document).remove();
        })

        $('.liveChatClose').click(function () {
            liveChat.server.endChat($.connection.hub.id);
            $('#iframeLiveChat, #liveChatOverlay, #iframeLiveChatBrowse', window.parent.document).remove();
        })
        
        $('#btn-liveChatSendMessage').click(function () {
            liveChatClient.sendOffLineMessage($('#textLiveChatMessageName').val(), $('#textLiveChatMessageEmail').val(), $('#textLiveChatMessageText').val());
        });

        $('#textLiveChatMessage').css('width', ($(window).width() - 95) + 'px');
        $('.modal-body').height($(window).height() - 125);

        var liveChatMessages = {

            appendMessageToChatWindow: function (sender, message) {
                $('#liveChatText').append('<div class="messageContainer row-fluid"><div class="span4"><i class="icon-chevron-right"></i>&nbsp;&nbsp;<strong>' + sender + '</strong><br /><span class="time" title="' + new Date().toISOString() + '">' + new Date().toISOString() + '</span></div><div class="span8">' + message + '</div></div>');
                $("#liveChatText").animate({ scrollTop: $('#liveChatText')[0].scrollHeight }, 1000);
            },

            appendInfoMessageToChatWindow: function (message) {
                $('#liveChatText').append('<div class="alert alert-info">' + message + '</div>');
                $("#liveChatText").animate({ scrollTop: $('#liveChatText')[0].scrollHeight }, 1000);
            },

            appendAlertMessageToChatWindow: function (message) {
                $('#liveChatText').append('<div class="alert">' + message + '</div>');
                $("#liveChatText").animate({ scrollTop: $('#liveChatText')[0].scrollHeight }, 1000);
            }

        };

        liveChat.client.postMessage = function (message, senderId, senderName, messageType) {

            operatorConnectionId = senderId;
            liveChatClient.config.operatorConnectionId = senderId;

            if (messageType != '') {
                switch (messageType) {
                    case 'info':
                        liveChatMessages.appendInfoMessageToChatWindow(message);
                        break;
                }
            } else {
                liveChatMessages.appendMessageToChatWindow(senderName, message);
            }

            if (senderId != '') {
                $('#liveChatInput').show();
                $('#postChatInput').hide();
            } else {
                $('#liveChatInput').hide();
                $('#postChatInput').show();
            }

            $("#liveChatText").animate({ scrollTop: $('#liveChatText')[0].scrollHeight }, 1000);
            $("span.time").prettyDate();
            $('#typing-indicator-client').slideUp();
            clearTimeout(typingIndicationTimer);

            keyStrokeCount = 0;

        };

        liveChat.client.liveChatStatus = function (status) {

            if (!inChat)
            {
                if (status == 'online') {
                    $('#modalLiveChatRegister').show();
                    $('#modalLiveChatOffLine').hide();
                } else {
                    $('#modalLiveChatOffLine').show();
                    $('#modalLiveChatRegister').hide();
                }
            }

        };

        liveChat.client.updateSessionId = function (sessionId) {
            liveChatClient.config.sessionId = sessionId;
        };

        liveChat.client.isTyping = function () {
            $('#typing-indicator-client').slideDown();
            clearTimeout(typingIndicationTimer);
            typingIndicationTimer = setTimeout(function () { $('#typing-indicator-client').slideUp(); }, 2000);
        };

        liveChat.client.receiveWebLink = function (url) {

            if (liveChatClient.config.coBrowsing == true) {
                
                $('#iframeLiveChatBrowse', window.parent.document).attr('src', url);

            } else {

                $('#liveChatOverlay', window.parent.document).remove();
                $('#iframeLiveChat', window.parent.document).css({ 'width': ($(window.parent.document).width() - 2) + 'px', 'position': 'absolute', 'left': '400px', 'top': '300px', 'height': '300px' });
                $('#liveChatText').css('height', ($(window).height() - 130) + 'px');
                $('#textLiveChatMessage').css('width', ($(window).width() - 95) + 'px');

                $('<iframe />', {
                    id: "iframeLiveChatBrowse",
                    src: url
                }).appendTo(parent.$("body"));

                $('#iframeLiveChatBrowse', window.parent.document).bind('load', function () {
                    window.parent.document.getElementById("iframeLiveChat").contentWindow.liveChatClient.updateCoBrowsingLink(this.contentWindow.location);
                });

                $('#iframeLiveChatBrowse', window.parent.document).css({ 'border-top': 'solid 1px #666', 'z-index': '1000000001', 'width': $(window.parent.document).width() + 'px', 'position': 'absolute', 'left': '0px', 'top': '300px', 'height': ($(window.parent.document).height() - 301) + 'px' });
                liveChatClient.config.coBrowsing = true;

            }

            liveChatMessages.appendInfoMessageToChatWindow('You are now browsing: ' + url);

        };

        $.connection.hub.start().done(function () {

            liveChat.server.checkStatus(liveChatClient.config.clientIP);

            $('#btn-liveChat').click(function () {
                $('#modalLiveChatRegister').show();
                $('#liveChatInput').hide();
                $('#postChatInput').hide();
            });

            $('#btn-liveChatStart').click(function () {

                $('#modalLiveChatRegister').hide();
                $('#modalLiveChat').show();

                $('#modalLiveChat').height($(window).height());
                $('#liveChatText').css('height', ($(window).height() - 130) + 'px');

                $('#liveChatText').html('');
                clientName = $('#textLiveChatName').val();

                var newClient = {
                    Name: clientName,
                    ConnectionId: $.connection.hub.id,
                    ConnectedAt: new Date().toISOString(),
                    Email: $('#textLiveChatEmail').val(),
                    Browser: $.browser.className,
                    OperatingSystem: $.os.name,
                    Url: parent.window.location.href,
                    Ip: liveChatClient.config.clientIP
                };

                liveChat.server.join(newClient);
                liveChatMessages.appendAlertMessageToChatWindow('An operator will be with you shortly...');

                $("span.time").prettyDate();
                $('#btnEndChat').show();

                $("#textLiveChatMessage").keypress(function (e) {
                    if (e.which == 13) {
                        e.preventDefault();
                        $('#btnSendChatMessage').trigger('click');
                    }

                    keyStrokeCount++;
                    if (keyStrokeCount > 10) {
                        liveChat.server.isTyping($.connection.hub.id, operatorConnectionId)
                        keyStrokeCount = 0;
                    }

                });

                inChat = true;

            });

            $('#btnSendChatMessage').click(function () {

                var message = $('#textLiveChatMessage').val();

                if (message != '') {
                    liveChatMessages.appendMessageToChatWindow(clientName, message);
                    liveChat.server.sendMessage(message, operatorConnectionId, $.connection.hub.id, clientName, '', liveChatClient.config.sessionId);
                    $("#liveChatText").animate({ scrollTop: $('#liveChatText')[0].scrollHeight }, 1000);
                    $("span.time").prettyDate();
                    $('#textLiveChatMessage').val('');
                }

            })

        });

    }
}